package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.mapper.ItemParamMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.pojo.ItemParam;
import com.jt.vo.ItemParamVO;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author YuBaoFu
 * @create 2024/11/11
 * @description
 */
@Service
public class ItemServiceImpl implements ItemService{

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemDescMapper itemDescMapper;

    @Autowired
    private ItemParamMapper itemParamMapper;

    /**
     * 1.使用分页查询
     *      1.1手写sql
     *      1.2利用MP
     * @param pageResult
     * @return
     */
    @Override
    public PageResult findItemList(PageResult pageResult) {
        IPage page = new Page(pageResult.getPageNum(),
                pageResult.getPageSize());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        //用户是否传递参数
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"title", pageResult.getQuery());

        page = itemMapper.selectPage(page,queryWrapper);
        long total = page.getTotal();
        List<Item> itemList = page.getRecords();
        return pageResult.setTotal(total).setRows(itemList);
    }

    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        ObjectMapper Mapper = new ObjectMapper();
        /*添加商品*/
        Item item = itemVO.getItem();
        item.setStatus(true);
        itemMapper.insert(item);
        /*添加商品详情*/
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
        /*添加商品动静态参数*/
        ItemParam itemParam = itemVO.getItemParam();
        ItemParamVO[] dynamicArray = itemParam.getDynamicArray();
        ItemParamVO[] staticArray = itemParam.getStaticArray();

        try {
            String dynamic = Mapper.writeValueAsString(dynamicArray);
            String staticArgs = Mapper.writeValueAsString(staticArray);
            itemParam.setId(item.getId()).setDynamicArgs(dynamic).setStaticArgs(staticArgs);
            itemParamMapper.insert(itemParam);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }


}
